import roleForm from "../role.vue";
import { bindRole, getUserList, resetPassword, type User } from "@/api/system";
import type { PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, h } from "vue";
import { DictTag } from "@/components/ReDict";
import { addDialog } from "@/components/ReDialog/index";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";

export function userUser() {
  const form = reactive<User>({
    current: 1,
    size: 20,
    name: "",
    username: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "姓名",
      prop: "name"
    },
    {
      label: "用户名",
      prop: "username"
    },
    {
      label: "状态",
      prop: "status",
      cellRenderer: ({ row, props }) => (
        <DictTag size={props.size} value={row.status} code="User_Status" />
      )
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    form.size = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    form.current = val;
    onSearch();
  }

  function onSearch() {
    loading.value = true;
    getUserList(form)
      .then(data => {
        dataList.value = data.records;
        pagination.total = data.total;
        pagination.pageSize = data.size;
        pagination.currentPage = data.current;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const resetForm = (formEl: any) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  function resetPwd(id: string) {
    ElMessageBox.confirm("确定重制密码?", "警告", {
      type: "warning"
    }).then(() => {
      resetPassword(id)
        .then(res => {
          ElMessageBox.alert(
            h("p", null, [
              h("span", null, "密码重制成功："),
              h("i", { style: "color: teal" }, res),
              h("br", null, null),
              h("i", { style: "color: red" }, "弹窗关闭后密码将不再可见")
            ]),
            "系统提示"
          ).then();
        })
        .catch(err => {
          message(`密码重制失败:${err}`, { type: "error" });
        });
    });
  }

  function openRoleDialog(userId: string) {
    addDialog({
      title: `分配角色`,
      props: {
        formInline: {
          userId: userId
        }
      },
      width: "30%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline;

        function submit() {
          bindRole(curData.userId, curData.role)
            .then(() => {
              message("角色分配成功", { type: "success" });
              done(); // 关闭弹框
            })
            .catch(err => {
              message(`角色分配失败:${err}`, { type: "error" });
            });
        }

        if (curData.role == null || curData.role.length === 0) {
          ElMessageBox.confirm("确定清空该用户角色?", "警告", {
            type: "warning"
          }).then(() => {
            submit();
          });
        } else {
          submit();
        }
      }
    });
  }

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    resetPwd,
    openRoleDialog,
    handleSizeChange,
    handleCurrentChange
  };
}
